package com.oocl.producer;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.command.ActiveMQQueue;
import org.json.JSONObject;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.oocl.dao.pojo.Book;
import com.oocl.file2bookdata.FileToBookData;

public class BookData2Json {
	
	public void bookData2Json(List<Book> bList){	
		ObjectMapper mapper=new ObjectMapper();
		for (int i = 0; i < bList.size(); i++) {
			String s;
			try {
				s = mapper.writeValueAsString(bList.get(i));
				jsonProducer(s);
			} catch (JsonProcessingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
	}
	public void jsonProducer(String s){
		Connection con=null;
		ConnectionFactory factory=new ActiveMQConnectionFactory("tcp://127.0.0.1:61616");
		Destination queue=new ActiveMQQueue("Lionel");
		try {
			con=factory.createConnection();
			con.start();
			Session sen=con.createSession(false, Session.AUTO_ACKNOWLEDGE);
			MessageProducer mp=sen.createProducer(queue);
			TextMessage msg=sen.createTextMessage(s);
			mp.send(msg);
			mp.close();
			sen.close();
			con.close();
		} catch (JMSException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
	
	public static void main(String[] args) throws Exception{
//		List<Book> bList=new ArrayList<Book>();
//		FileToBookData ftd=new FileToBookData();
//		bList=ftd.getBookDataFromFile("book.data");
//		BookData2Json bd2j=new BookData2Json();
//		bd2j.bookData2Json(bList);
		ExecutorService pool = Executors.newFixedThreadPool(5);
		pool.execute(new BookData2JSonWithThread());
		pool.shutdown();
	}
	

}
